'''
Created on 21/04/2009

@author: eh01
'''
from yarra.datastore import dsconstants, dsofactory
from yarra.event import eventconstants
from yarra.event.event import Event
from yarra.event.eventhandler import BaseEventHandler
from yarra.event.eventmanager import EventManager
from yarra.logging import yarralogging
import httplib
import logging
import os

class HTTPRequestGETLoggingHandler(BaseEventHandler):
    '''
    classdocs
    '''

    __LEVELS = {logging.NOTSET:'NOTSET',
                logging.DEBUG:'DEBUG',
                logging.INFO:'INFO',
                logging.WARNING:'WARNING',
                logging.ERROR:'ERROR',
                logging.CRITICAL:'CRITICAL'}

    def __init__(self):
        '''
        Constructor
        '''
    
    def do(self, data):
        dso = data
        http_request = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_HTTP_REQUEST).get_literal()
        lock = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_LOCK).get_literal()                    
        event_type = eventconstants.HTTP_RESPONSE_EVENT_TYPE
        # get the path of the appropriate html template
        
        relative_path = "../../../pages/hub/logging.html"
        
        html_content = "<table>"
        loggers = yarralogging.get_loggers()
        for logger_name in loggers.keys():
            logger = loggers[logger_name]
#            current_level = logger.getEffectiveLevel()
            current_level = logger.level
            html_content += "<tr><td>" + str(logger_name) + "</td><td>"
            html_content += "<select name='logger_" + str(logger_name) + "'>"
            for level in self.__LEVELS.keys():
                if level == current_level:
                    html_content += "<option value='" + str(level) + "' selected='selected'>" + self.__LEVELS[level] + "</option>"
                else:
                    html_content += "<option value=" + str(level) + ">" + self.__LEVELS[level] + "</option>"
            html_content += "</select></td></tr>"
        html_content += "</table>"
        # get the html
        template_path = os.path.join(os.path.dirname(__file__), relative_path)
        file = open(template_path)
        html_template_string = file.read()
        html_string = html_template_string.replace('${content}', html_content)
        # create new dso        
        new_dso = dsofactory.create_dso_for_im_http_response_handler(httplib.OK, 
                                                               'text/html', 
                                                               html_string, 
                                                               http_request, 
                                                               lock)            
        event = Event(event_type, new_dso)
        EventManager().add_event(event)         